package com.lavida.project.system.file.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lavida.common.utils.security.ShiroUtils;
import com.lavida.framework.aspectj.lang.annotation.Log;
import com.lavida.framework.aspectj.lang.enums.BusinessType;
import com.lavida.framework.web.controller.BaseController;
import com.lavida.framework.web.page.TableDataInfo;
import com.lavida.project.common.DownLoadUtils;
import com.lavida.project.system.file.domain.Profiles;
import com.lavida.project.system.file.service.ProfilesService;
import com.lavida.project.system.user.domain.User;
import com.lavida.project.system.user.service.IUserService;

@Controller
@RequestMapping("/system/comfile")
public class ProfilesController extends BaseController{
	private String prefix = "system/comfile";
	@Autowired
	private ProfilesService cProfileService;
	@Autowired
	private IUserService userService;
	@RequiresPermissions("data:comfile:view")
	@RequestMapping()
	public String comfile(ModelMap mmap) {
		User user  = ShiroUtils.getSysUser();
		User user1 = userService.selectUserById(user.getUserId());
		mmap.put("user", user1);
		return prefix+"/comfile";
	}
	@RequiresPermissions("data:comfile:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Profiles cProfile,HttpServletRequest request) {
		String str = request.getParameter("filename");
		cProfile.setFilename(str);
		cProfile.setRela_sys(str);
		startPage();
		List<Profiles> selectcomfile = cProfileService.selectcomfile(cProfile);
		return getDataTable(selectcomfile);
	}
	@RequiresPermissions("data:comfile:add")
	@Log(title = "参数管理", businessType = BusinessType.INSERT)
	@PostMapping("/showAddComfile")
	public String showAddComfile(@RequestParam("fujian2") MultipartFile file,Profiles cProfiles,HttpServletRequest request) throws IllegalStateException, IOException {
		try {
			if (file.isEmpty()) {
				cProfiles.setFujian("");
		        cProfiles.setFujianPath( "");
			}else {
		        String path = filePath(request);
		        //System.out.println("path>>>>>>"+path);
		        String originalFilename=file.getOriginalFilename();
		        String uuid=UUID.randomUUID().toString().replace("-","");
		        String filename=uuid+"_"+originalFilename.replace(" ", "");
		        file.transferTo(new File(path,filename));
		        cProfiles.setFujian(originalFilename.replace(" ", ""));
		        cProfiles.setFujianPath(filename.replace(" ", ""));
			}
		
        String[] syString = request.getParameterValues("rela_sys") ;
        String sys_sl = "";
        if(syString!=null) {
	        for(int i = 0;i<syString.length;i++) {
	        	/*Profiles pdis = cProfileService.getProfiles(Integer.valueOf(syString[i]));*/
	        	if(i!=syString.length-1) {
	        		sys_sl=sys_sl+syString[i]+",";
	            	System.out.println(sys_sl.toString());
	        	}else if(syString[i]==""||syString[i].equals("")) {
	        		continue;
	        	}else {
	        		sys_sl=sys_sl+syString[i];
	        	}
	        }
        }
        cProfiles.setRela_sys(sys_sl);
       
        cProfileService.insertcomfile(cProfiles);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "redirect:/system/comfile";
	}
	@RequiresPermissions("data:comfile:update")
	@Log(title = "参数管理", businessType = BusinessType.UPDATE)
	@PostMapping("/showUpdateComfile")
	public String showUpdateComfile(@RequestParam("fujian2") MultipartFile file,Profiles cProfiles,HttpServletRequest request) throws Exception {
		Profiles profiles = cProfileService.getProfiles(cProfiles.getId());
		if(file.isEmpty()){
			cProfiles.setFujian(profiles.getFujian());
	        cProfiles.setFujianPath(profiles.getFujianPath());
		}else {
			String path=filePath(request);
	        String originalFilename=file.getOriginalFilename();
	        String uuid=UUID.randomUUID().toString().replace("-","");
	        String filename=uuid+"_"+originalFilename.replace(" ", "");
	        file.transferTo(new File(path,filename));
	        System.out.println("文件路径:"+path+" 原文件名: "+originalFilename+"  组合文件名: "+
	        filename+"存储文件名"+originalFilename.replace("", "")+"存储文件路径"+filename.replace("", ""));
	        cProfiles.setFujian(originalFilename.replace(" ", ""));
	        cProfiles.setFujianPath(filename.replace(" ", ""));
		}
		  String[] syString = request.getParameterValues("rela_sys") ;
		  String sys_sl = "";
		  if(syString!=null) {
			  for(int i = 0;i<syString.length;i++) {
		        	if(i!=syString.length-1) {
		        		sys_sl=sys_sl+syString[i]+",";
		        	}else if(syString[i]==""||syString[i].equals("")) {
		        		continue;
		        	}else {
		        		sys_sl=sys_sl+syString[i];
		        	}
		        }
		  }
	        cProfiles.setRela_sys(sys_sl);
	        cProfileService.updatecomfile(cProfiles);
		return "redirect:/system/comfile";
	}
	@RequestMapping("/download")
	public void download(String fileRealname,String fileVmname,HttpServletResponse response,HttpServletRequest request) {
        String string=request.getHeader("User-Agent");
        String Uploadfilename=null;
        try {
			Uploadfilename= DownLoadUtils.getFileName(string,fileVmname);
			System.out.println(Uploadfilename);	

	        response.setHeader("Content-disposition","attachment;filename="+Uploadfilename);
	        String fileVmPath=filePath(request);
	        System.out.println(String.format("%s\\%s",fileVmPath,fileRealname));
	        ServletOutputStream s = response.getOutputStream();
	        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(String.format("%s/%s",fileVmPath,fileRealname)));
	        int a;
	        byte[] bytes=new byte[1024];
	        while ((a = bufferedInputStream.read(bytes))!=-1){
	            s.write(bytes,0,a);
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@RequiresPermissions("data:comfile:delete")
	/*@RequiresPermissions("data:comfile:delete")*/
	@Log(title = "参数管理", businessType = BusinessType.DELETE)
	@PostMapping("/delete")
	@ResponseBody
	public Map<String, String> delete(@RequestParam("ids[]")int[] ids){
		//定义一个Map集合，最终是为了把这个Map集合转换成json数据
		Map<String, String> result = new HashMap<String, String>();
		cProfileService.deletecomfile(ids);
		result.put("msg", "删除成功");
		return result;
	}
	
	@PostMapping("/getProfiles")
	@ResponseBody
	public Map<String, Object> getProfiles(int id){
		Map<String, Object> result = new HashMap<>();
		Profiles profiles = cProfileService.getProfiles(id);
		System.out.println(profiles);
		result.put("profiles", profiles);
		return result;
	}
	  private static String filePath(HttpServletRequest request){
	        // 先获取到要上传的文件目录
	        String path = request.getSession().getServletContext().getRealPath("/annex");

	        // 创建File对象，一会向该路径下上传文件
	        File file = new File(path);
	        System.out.println(file);
	        // 判断路径是否存在，如果不存在，创建该路径
	        if(!file.exists()) {
	            file.mkdirs();
	        }
	        return path;
	    }
}
